import React, { useEffect, useState, useRef } from 'react'
//导入axios
import axios from 'axios'
import { Link } from 'react-router-dom'
export default function Book() {
    //创建容器
    let bname = useRef(); // {current:undefined}
    //创建一个状态数据
    let [booklists, setBooklists] = useState([]); // 0x100
    //调用（在组件完成挂载的时候）
    useEffect(() => {
        //异步任务
        async function getAllBooks() {
            //同源请求：当协议、域名、端口号都一致的时候
            //只要是违反了任何一个条件就会产生跨域(JSONP，CORS，Proxy)
            //现在的url:http://localhost:3000/
            //目标的url:http://localhost:5000/api/books => http://localhost:5000/books
            let { data } = await axios.get('/api/books'); //0x200
            setBooklists(data);
        }
        //调用函数
        getAllBooks();
    }, []);
    //声明事件函数
    let searchBook = async () => {
        //获取文本框中的value值
        let name = bname.current.value;
        //发送请求
        let { data } = await axios.get('/api/books', {
            params: { name }
        });
        setBooklists(data);
    }
    return (
        <div className='booklists'>
            <h3>图书列表</h3>
            <hr />
            <p className='search'>请输入图书名称：<input type="text" ref={bname} />&nbsp;<button onClick={searchBook}>搜索</button></p>
            <ul>
                {
                    booklists.map(item => {
                        return (
                            //路由中传递请求字符串
                            <Link to={`/bookOne`} state={{ id: item.id, a: 1, b: 2, c: 3 }} key={item.id}><li>
                                <img src={'/image/' + item.img} alt="" />
                                <p className='bname'>{item.name}</p>
                            </li></Link>
                        )
                    })
                }
            </ul>
        </div>
    )
}
